/**
 * 颜色饱和度修改
 */
export default function lightenColor(color: string, rn: number, gn: number, bn: number) {
  // 改变颜色
  function changeColor([r, g, b]: number[]) {
    r = Math.min(255, Math.round(r + rn))
    g = Math.min(255, Math.round(g + gn))
    b = Math.min(255, Math.round(b + bn))

    return `${r},${g},${b}`
  }

  // 将16进制颜色转换为RGB
  if (color.startsWith('#')) {
    let hex = color.replace(/^#/, '')
    if (hex.length === 3) {
      hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
    }
    const num = Number.parseInt(hex, 16)
    return changeColor([num >> 16, (num >> 8) & 255, num & 255])
  }

  // 处理RGB颜色
  if (color.startsWith('rgb')) {
    return changeColor(
      color
        .slice(color.indexOf('(') + 1, color.lastIndexOf(')'))
        .split(',')
        .map(Number)
    )
  }

  if (/\d* *, *\d*/g.test(color)) {
    return changeColor(color.replaceAll(' ', '').split(',').map(Number))
  }

  return color // 如果无法处理，返回原始输入颜色
}

export function hexToRgb(color: string) {
  let hex = color.replace(/^#/, '')
  if (hex.length === 3) {
    hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
  }
  const num = Number.parseInt(hex, 16)
  return [num >> 16, (num >> 8) & 255, num & 255]
}

export const rgbToHsl = ([r, g, b]: number[]) => {
  ;[r, g, b] = [r / 255, g / 255, b / 255]
  const max = Math.max(r, g, b),
    min = Math.min(r, g, b)
  const d = max - min
  const l = (max + min) / 2
  const s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1))
  let h = 0
  if (d !== 0) {
    switch (max) {
      case r:
        h = (g - b) / d + (g < b ? 6 : 0)
        break
      case g:
        h = (b - r) / d + 2
        break
      case b:
        h = (r - g) / d + 4
        break
    }
    h /= 6
  }

  return [Math.round(h * 360), Math.round(s * 100), Math.round(l * 100)]
}

export function hslToRgb([h, s, l]: number[]) {
  h /= 360
  s /= 100
  l /= 100

  let r, g, b

  if (s === 0) {
    r = g = b = l
  } else {
    const hue2rgb = (p: number, q: number, t: number) => {
      if (t < 0) t += 1
      if (t > 1) t -= 1
      if (t < 1 / 6) return p + (q - p) * 6 * t
      if (t < 1 / 2) return q
      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6
      return p
    }

    const q = l < 0.5 ? l * (1 + s) : l + s - l * s
    const p = 2 * l - q

    r = Math.round(hue2rgb(p, q, h + 1 / 3) * 255)
    g = Math.round(hue2rgb(p, q, h) * 255)
    b = Math.round(hue2rgb(p, q, h - 1 / 3) * 255)
  }

  return [r, g, b]
}
